package com.cgsd.heyu.http;

import io.reactivex.observers.DefaultObserver;

/**
 * @author xiaoxing
 * Created by Administrator on 2018/3/25.
 * 显示进度
 */
public abstract class BaseRxFileSubscribe<T> extends DefaultObserver<T> {

    @Override
    public void onNext(T value) {
        onSuccess(value);
    }


    @Override
    public void onError(Throwable e) {
        ExceptionHandler.ResponseThrowableException responseThrowable;
        if (e instanceof Exception){
            //访问获得对应的Exception
            responseThrowable = ExceptionHandler.handleException(e);
            onFail(new ErrorMessage(responseThrowable.code,responseThrowable.message));
        }else {
            //将Throwable 和 未知错误的status code返回
            responseThrowable = new ExceptionHandler.ResponseThrowableException(e,ExceptionHandler.Error.UNKNOWN);
            onFail(new ErrorMessage(responseThrowable.code,responseThrowable.message));
        }
    }

    /**
     * 监听进度的改变
     */
    public void onProgressChange(long bytesWritten, long contentLength) {
        onProgress((int) (bytesWritten*100 / contentLength));
    }

    @Override
    public void onComplete() {

    }

    /**
     * 成功回调
     * @param t 返回数据
     */
    public abstract void onSuccess(T t);

    /**
     * 失败回调
     * @param error  错误数据
     */
    public abstract void onFail(ErrorMessage error);

    /**
     * 上传进度回调
     * @param progress 数值
     */
    public abstract void onProgress(int progress);

}
